package com.hxb.hxbgateway.config;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

@Component
public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory {
    private static final String HEADER_NAME = "X-Forwarded-Prefix";
    @Override
    public GatewayFilter apply(Object config) {
        return ((exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            if(!StringUtils.endsWithIgnoreCase(path,SwaggerProvider.API_URL)){
                return chain.filter(exchange);
            }
            String basePath = path.substring(0,path.lastIndexOf(SwaggerProvider.API_URL));
            ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME,basePath).build();
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
            System.out.println(newRequest);
            System.out.println(newExchange);
            return  chain.filter(newExchange);
        });
    }
}
